import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_storage.dart';
import 'package:xindong/common/xindong_types.dart';
import 'package:xindong/handle/xindong_user_handle.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_database_singleton.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/manager/xindong_tencent_singleton.dart';
import 'package:xindong/manager/xindong_window_singleton.dart';
import 'package:xindong/models/xindong_push_class.dart';
import 'package:xindong/models/user/xindong_base_user.dart';
import 'package:xindong/models/user/xindong_wode_user.dart';
import 'package:xindong/models/user/xindong_user.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/tab_chats/controller/xindong_liaotian_vm.dart';
import 'package:xindong/routes/tab_home/controller/xindong_home_tab_controller.dart';
import 'package:xindong/routes/tab_mine/xindong_wode_http.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';

class XinDongUserController extends GetxController {
  static XinDongUserController get to => Get.find();
  final String updateIdOfLoginStatus = "loginStatus";

  // 请求
  final _mineHandle = XinDongWoDeHandle();
  final _userHandle = XinDongUserHandle();

  // obs监听是否会员属性
  final RxBool isNoble = RxBool(false);

  String? loginId;
  String? loginSig;
  String? sex;
  XinDongWoDeUser? userInfo;
  List<XinDongPushClass>? pushList;

  // 用户登录且信息完善
  // 当前条件为id、sig有效即可
  bool get isUserCompleted {
    return !TextUtil.isEmpty(loginId) && !TextUtil.isEmpty(loginSig);
  }

  // 金币余额
  String get balance {
    return "${userInfo?.volley ?? 0}";
  }

  // 积分收益
  String get income {
    return "${userInfo?.score_price ?? 0}";
  }

  XinDongUserController() {
    // accountUser = XinDongStorage.instance.getAccount();
    loginId = XinDongStorage.instance.getString(XinDongStorageKey.loginId);
    loginSig = XinDongStorage.instance.getString(XinDongStorageKey.loginSig);
    sex = XinDongStorage.instance.getString(XinDongStorageKey.sex);
  }

  //
  // XinDongAccount? accountUser;
  //
  // bool isLogin() {
  //   if (accountUser != null && accountUser!.token.isNotEmpty) {
  //     return true;
  //   }
  //   return false;
  // }

  // 服务端token
  // String get serverToken {
  //   if (!TextUtil.isEmpty(accountUser?.token)) {
  //     return accountUser!.token;
  //   }
  //   XinDongAccount? account = XinDongStorage.instance.getAccount();
  //   if (!TextUtil.isEmpty(account?.token)) {
  //     return account!.token;
  //   }
  //   return "";
  // }

  // 发布权限
  // bool get isPushMoment {
  //   if (accountUser?.dynamicStatus == 1) {
  //     return true;
  //   } else {
  //     return false;
  //   }
  // }

  // 登录成功需要操作
  void commonLoginSuccessfulHandler({
    required String userId,
    required String sig,
    required String gender,
    bool needJump = true,
  }) {
    loginId = userId;
    loginSig = sig;
    sex = gender;

    // 保存用户信息
    XinDongStorage.instance.saveString(XinDongStorageKey.loginId, loginId!);
    XinDongStorage.instance.saveString(XinDongStorageKey.loginSig, loginSig!);
    XinDongStorage.instance.saveString(XinDongStorageKey.sex, sex!);

    XinDongTencentSingleton.instance.login();
    // 登录成功需要设置的操作
    requestUserInfo();

    // 页面切换
    XinDongPageSingleton.instance.jumpToTabBarYeMian(needJump: needJump);
  }

  /// 用户退出，不论成功失败
  Future<void> userLogout() async {
    // 退出前处理
    await _commonLogoutBeforeHandler();
    if (!TextUtil.isEmpty(loginId)) {
      // 清数据前要请求操作，清了再请求顺序有问题
      _mineHandle.setOnline(state: UserState.normal);
    }
    _commonLogoutAfterHandler();
    XinDongPageSingleton.instance.jumpToLoginYeMian();
    return Future.value();
  }

  /// 被动退出:103,im失效，在其他设备登录等
  void passiveLogout({String showTips = ""}) {
    // 不能请求，只需清数据
    _commonLogoutAfterHandler();
    XinDongPageSingleton.instance.jumpToLoginYeMian(showTips: showTips);
  }

  /// 公共处理退出账号前需要做的事情
  /// 带请求
  Future<void> _commonLogoutBeforeHandler() async {
    if (!TextUtil.isEmpty(loginId)) {
      // 清数据前要请求操作，清了再请求顺序有问题
      // mineHandle.userResetPush();
      _mineHandle.setOnline(state: UserState.normal);
    }
    // 通话结束
    await XinDongCallController.to.hangup();
    // // 退出房间
    // await XinDongRoomProvider.instance.onExitRoom();
    return Future.value();
  }

  /// 公共处理退出账号后需要清空的数据
  /// 不带请求
  void _commonLogoutAfterHandler() {
    XinDongLiaoTianVM.to.clear();
    XinDongHomeTabController.to.clear();
    XinDongDatabaseSingleton.instance.htmy_clear();
    // XinDongUserSingleton.instance.htmy_clear();
    // XinDongDialogQueue.instance.htmy_clear();
    // IM和删除数据放后面
    // 退出IM
    XinDongTencentSingleton.instance.logout();
    // 删除用户数据
    loginId = null;
    loginSig = null;
    sex = null;

    // 保存用户信息
    XinDongStorage.instance.saveString(XinDongStorageKey.loginId, "");
    XinDongStorage.instance.saveString(XinDongStorageKey.loginSig, "");
    XinDongStorage.instance.saveString(XinDongStorageKey.sex, "");
    update();
  }
}

extension UserControllerClass on XinDongUserController {
  XinDongUser get callUser {
    try {
      return XinDongUser.fromJson(XinDongConversionUtil.modelToMap(userInfo));
    } catch (e) {
      return XinDongUser()
        ..user_id = loginId
        ..sex = sex;
    }
  }

  // 当前用户基类模型
  XinDongBaseUser get baseUser {
    try {
      return XinDongBaseUser.fromJson(XinDongConversionUtil.modelToMap(userInfo));
    } catch (e) {
      return XinDongBaseUser()
        ..user_id = loginId
        ..sex = sex;
    }
  }

//
// // 当前用户模型
// XinDongUserClass get mineUserClass {
//   try {
//     return XinDongUserClass.fromJson(XinDongConversionTool.modelToMap(accountUser?.user));
//   } catch (e) {
//     return XinDongUserClass()
//       ..uid = 0
//       ..userType = UserType.normal;
//   }
// }
}

extension UserControllerHandle on XinDongUserController {
  // 更新金币
  void updateCoins(dynamic volley) async {
    if (userInfo?.volley != null && volley != null) {
      userInfo?.volley = volley;
      update();
    }
  }

  // 扣除金币
  void decrementCoins(double coins, {bool needRequest = true}) async {
    if (userInfo?.volley != null) {
      userInfo?.volley -= coins;
      if (userInfo?.volley < 0) {
        needRequest = true;
      }
    } else {
      needRequest = true;
    }
    if (needRequest) {
      // 需要请求刷新账户
      requestUserVolley();
    } else {
      update();
    }
  }

  // 更新IM签名
  void updateSig() async {
    if (!isUserCompleted) {
      return;
    }
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userSig,
      method: XinDongHttpMethod.post,
    );
    if (object.code == XinDongServerStatus.success) {
      loginSig = "${object.result["tencentId"]}";
      XinDongStorage.instance.saveString(XinDongStorageKey.loginSig, loginSig!);
    }
  }
  
  // 请求用户信息
  Future<void> requestUserInfo() async {
    if (!isUserCompleted) {
      return;
    }
    final model = await _mineHandle.userInfo();
    if (model != null) {
      userInfo = model;
      isNoble.value = model.is_noble == 1;
      if (model.screen_capture == 1) {
        XinDongWindowSingleton.instance.close();
      } else {
        XinDongWindowSingleton.instance.open();
      }
      update();
    }
    return Future.value();
  }

  // 请求用户余额
  void requestUserVolley() async {
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userVolley,
      method: XinDongHttpMethod.post,
    );
    if (object.code == XinDongServerStatus.success) {
      userInfo?.volley = object.volley;
      update();
    }
  }

  // 请求用户余额
  void requestUserScore() async {
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userScore,
      method: XinDongHttpMethod.post,
    );
    if (object.code == XinDongServerStatus.success) {
      userInfo?.score = object.data["score"];
      userInfo?.money = object.data["money"];
      update();
    }
  }

  // 配置
  void requestConfig() async {
    final model = await _userHandle.userConfig(userId: loginId);
    if (model != null) {
      userInfo?.configPersonal = model;
      update();
    }
  }

  // 推送
  void requestPushList() async {
    final result = await _userHandle.userPushList();
    if (result.isNotEmpty) {
      pushList = result;
      update();
    }
  }

//   // 请求删除相册
//   void requestDeleteAlbum(XinDongUserAlbum albumClass) async {
//     AlertOptions.show(
//       content: '是否要删除该${albumClass.type == 1 ? '视频' : '照片'}',
//       buttonTow: '我再想想',
//       buttonOne: '确认删除',
//       onTabOne: () async {
//         bool result = await XinDongUserHandle.deleteAlbum(albumId: albumClass.id!);
//         if (result) {
//           // 我的相册移除
//           accountUser?.user.photo?.remove(albumClass);
//           requestUserInfo();
//         }
//       },
//       onTabTow: () {},
//     );
//   }
//
//   Future<void> userLogout() async {
//     XinDongStorage.instance.removeAccount();
//     Get.offAll(const XinDongTabYeMian());
//     await XinDongNetworking.instance.request(
//       XinDongApi.accountLogout,
//       method: XinDongHttpMethod.post,
//     );
//   }
//
//   // 注销账号
//   Future<bool> userDestroy(String title) async {
//     bool result = await XinDongUserHandle.userDestroy(title);
//     if (result) {
//       XinDongStorage.instance.removeAccount();
//     }
//     return result;
//   }
}
